<?php
namespace app\admin\controller;
use app\common\controller\AdminBase;
use think\DB;
/*广告管理*/
class Windows extends AdminBase{
	protected $beforeActionList = [
        'before_index'=>['only'=>'index'],
    ];
	function _initialize() {
		parent::_initialize();  
    }
	function index(){
		$this->assign("now",date("Y-m-d"));
		echo $this->fetch();
	}	
	function delete(){
		$id=input("id");
		db("Ad")->delete($id);
		$this->ajax_success("成功");
	}
	//新增设备
	function addEqui(){
		if(request()->isPost()){
			$shop_id=sp_get_current_shop_id();
			db("Equipment")->insert(array("shop_id"=>$shop_id,"mac_addr"=>input("mac"),"name"=>input("name"),"descs"=>input("descs")));
			$this->ajax_success("成功");	
		}else{
			echo $this->fetch();die;		
		}
	}
	//激活
	function activation(){
		$id=input("id");
		db("Ad")->where("id>0")->setField(array("is_activation"=>0));
		db("Ad")->where("id=$id")->setField(array("is_activation"=>1));
		$event=controller("api/JpusHelper");
		$model=db("Ad")->where("id=$id")->find();
		$equip_ids=$model['equip_ids'];
		if(empty($equip_ids)){
			$equip_ids="0";
		}
		$macs=db("Equipment")->where("id in($equip_ids)")->column("mac_addr");
        $new_macs = array();
        foreach ($macs as $mac) {
            $new_macs[] = str_replace(":", "", $mac);
        }
        $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
        $home_domain = $_SERVER['HTTP_HOST'];
        $model_url_arr = explode(",", $model["url"]);
        $url_arr = array();
        foreach ($model_url_arr as $url) {
            if (!empty($url)) {
                $url_arr[] = $http_type . $home_domain . $url;
            }

        }
		$event->tv($new_macs,$model['type'],implode(",", $url_arr));
		$this->ajax_success("成功");
	}
	/*卡列表数据*/
	function ajax_index(){
		$this->ajax($this->_ajax_index());
	}
	
	function add(){
		$shop_id=sp_get_current_shop_id();
		if(request()->isPost()){
			$equip_ids=$_POST['equip_ids'];
			if(empty($equip_ids)){
				$equip_ids=[];	
			}
			$url=input("url");
			if(!empty(input("title"))){
				$url=input("title");
			}
			db("Ad")->insert(array("name"=>input("name"),"descs"=>input("descs"),"type"=>input("type"),"url"=>$url,"equip_ids"=>implode(",", $equip_ids),"shop_id"=>$shop_id));
			$this->ajax_success("成功");
		}else{
			$equips=db("Equipment")->where("shop_id=$shop_id")->select();
			if(empty($equips)){
				$equips=[];	
			}
			$this->assign("equips",$equips);
			echo $this->fetch();
		}		
	}
	///////////////////////////////////////////////////////////////////////////////////
	/**
	 * 权限菜单
	 **/
	function before_index(){
		$auth_group=sp_get_auth_menu_3("10041008");
		$this->assign("menus",$auth_group);
	}
	
	/*获取卡数据*/
	private function _ajax_index(){
		$query=array(
				'name'=>array("field" =>"name","operator" =>"like"),
				);
		$draw=input("draw",0)+1;//请求时间		 
		$where_and=join(" and ",sp_get_param_sql(request()->isPost(),$query));
		
		$shop_id=sp_get_current_shop_id();
		if(!empty($shop_id)){
			$where_and.=" and shop_id=$shop_id";
		}
		
		$total=db("Ad")->where($where_and)->fetchsql(FALSE)->count(1);
		$list=db("Ad")->where($where_and)->order($this->get_order())->limit($this->get_limit())->fetchsql(FALSE)->select();
		
		return array('pageData'=>$list,'total'=>$total,"draw"=>$draw);
	}

	/**
     * tv盒子配置
     */
	public function tvConfig()
    {
        $shop_id = sp_get_current_shop_id();
        $box_config = db("tvbox_config")->where(array("shop_id" => $shop_id))->find();
        if (empty($box_config)) {
            $box_config = array();
        }
        $this->assign("config", $box_config);
        echo  $this->fetch();
    }

    public function tvConfigPost()
    {
        $shop_id = sp_get_current_shop_id();
        $is_open = input("is_open/d", 1);
        $bg_url = input("bg_url/s", "");
        $logo_url = input("logo_url/s", "");
        $welcome_tpl = input("welcome_tpl/s", "");

        if (empty($bg_url)) {
            $this->ajax_error("请上传背景图片");
        }
        if (empty($logo_url)) {
            $this->ajax_error("请上传logo图片");
        }
        if (empty($welcome_tpl)) {
            $this->ajax_error("请填写欢迎语");
        }
        if (strlen($bg_url) > 255) {
            $this->ajax_error("上传出错");
        }
        if (strlen($logo_url) > 255) {
            $this->ajax_error("上传出错");
        }
        if (mb_strlen($welcome_tpl) > 500) {
            $this->ajax_error("欢迎语不能超过500个字符");
        }
        //bg_url 和 logo_url为临时地址 需复制到实际地址
        if (!file_exists(ROOT_PATH . $bg_url) || !file_exists(ROOT_PATH . $logo_url)) {
            $this->ajax_error("上传文件不存在");
        }
        $bg_name = pathinfo(ROOT_PATH . $bg_url, PATHINFO_BASENAME );
        $logo_name = pathinfo(ROOT_PATH . $logo_url, PATHINFO_BASENAME );

        $dir_name =  "/data/upload/" . date("Ymd") . "/";
        if (!is_dir(ROOT_PATH . $dir_name)) {
            mkdir(ROOT_PATH . $dir_name);
        }
        $real_bg_url = $dir_name . $bg_name;
        $real_logo_url = $dir_name . $logo_name;

        $box_config = db("tvbox_config")->where(array("shop_id" => $shop_id))->find();
        if ($bg_url != $real_bg_url) {
            if (!copy(ROOT_PATH . $bg_url, ROOT_PATH . $real_bg_url)) {
                $this->ajax_error("上传出错");
            }
        }

        if ($logo_url != $real_logo_url) {
            if ( !copy(ROOT_PATH . $logo_url, ROOT_PATH .$real_logo_url)) {
                $this->ajax_error("上传出错");
            }
        }

        if (empty($box_config)) {
            db("tvbox_config")->insert(array("shop_id" => $shop_id, "is_open" => $is_open, "bg_url" => $real_bg_url, "logo_url" => $real_logo_url, "welcome_tpl" => $welcome_tpl));
        } else {
            db("tvbox_config")->where(array("shop_id" => $shop_id))->update(array("is_open" => $is_open, "bg_url" => $real_bg_url, "logo_url" => $real_logo_url, "welcome_tpl" => $welcome_tpl));
            //删除以前文件
            if ($box_config["bg_url"] != $real_bg_url) {
                if (file_exists(ROOT_PATH . $box_config["bg_url"])) {
                    unlink(ROOT_PATH . $box_config["bg_url"]);
                }
            }
            if ($box_config["logo_url"] != $real_logo_url) {
                if (file_exists(ROOT_PATH . $box_config["logo_url"])) {
                    unlink(ROOT_PATH . $box_config["logo_url"]);
                }

            }
        }


        $this->ajax_success("保存成功");
    }

    /**
     * 推送设备
     */
    public function pushTv()
    {
        $shop_id = sp_get_current_shop_id();
        $box_config = db("tvbox_config")->where(array("shop_id" => $shop_id))->find();
        if (empty($box_config)) {
            $this->ajax_tpl("请先保存TV盒子配置");
        }
        $equipments = db("equipment")->where(array("shop_id" => $shop_id, "type" => 3))->select();
        if (empty($equipments)) {
            $this->ajax_tpl("请先添加设备");
        }
        $this->assign("equipments", $equipments);
        echo $this->fetch();
    }

    /**
     * 推送操作
     */
    public function pushTvPost()
    {
        $shop_id = sp_get_current_shop_id();
        $box_config = db("tvbox_config")->where(array("shop_id" => $shop_id))->find();
        if (empty($box_config)) {
            $this->ajax_error("请先保存TV盒子配置");
        }
        $equip_ids = input('equip_ids/a');
        if (empty($equip_ids)) {
            $this->ajax_error("请选择推送设备");
        }
        $ids = array();
        foreach ($equip_ids as $id) {
            $ids[] = (int)$id;
        }
        $macs = db("equipment")->where(array("id" => array("in", $ids), "shop_id" => $shop_id, "type" => 3))->column("mac_addr");
        if (empty($macs)) {
            $this->ajax_error("推送设备选择错误");
        }
        $new_macs = array();
        foreach ($macs as $mac) {
            $new_macs[] = str_replace(":", "", $mac);
        }
        $event = controller("api/JpusHelper");
        $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
        $home_domain = $_SERVER['HTTP_HOST'];
        $data = array(
            "bg_url" => $http_type . $home_domain . $box_config['bg_url'],
            "logo_url" => $http_type .$home_domain . $box_config['logo_url']
        );
        $event->tv($new_macs, 4, implode(",", $data));
        $this->ajax_success("成功");
    }
}
